<template>
  <div>
    <van-search
      v-model="word"
      show-action
      label="商品"
      background="#ff734c"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <h5 style="font-size: 16px">历史记录</h5>
    <div class="histories">
      <div class="his" @click="clickHis(his)" v-for="his in hises" :key="his">
        {{his}}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      word: '',
      hises: localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
    }
  },
  methods: {
    clickHis (word) {
      // 点击历史记录进行搜索
      this.word = word
      this.onSearch()
    },
    onSearch () {
      // 跳转到 搜索结果页，并将所有的关键字传入=
      // 重新获取缓存 转换成数组 先数组 插入数据 再存回去
      let his = localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
      his.unshift(this.word)
      his = [...new Set(his)]
      // 控制长度
      if (his.length > 5) {
        his.pop()
      }
      localStorage.setItem('his', JSON.stringify(his))

      this.$router.push({
        path: '/searchList',
        query: {
          word: this.word
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.histories{
  display: flex;
  flex-wrap: wrap;
  .his{
    line-height: 30px;
    font-size: 14px;
    color: #666;
    margin: 0 10px;
  }
}
</style>
